<template>
  <div class="box">
    <el-form
      :model="data.ruleForm"
      :rules="rules"
      ref="ruleFormRef"
      label-width="400px"
      class="demo-ruleForm"
      size="large"
      label-position="left"
      validate-on-rule-change
      style="width: 85%"
    >
      <el-form-item label="标题" prop="title" style="width: 100%">
        <el-input
          style="width: 100%"
          type="text"
          v-model="data.ruleForm.title"
          placeholder="输入标题..."
        ></el-input>
      </el-form-item>

      <el-form-item label="内容" prop="content" style="width: 100%">
        <v-md-editor
          v-model="data.ruleForm.content"
          height="430px"
          placeholder="请输入内容"
          :disabled-menus="[]"
          @upload-image="handleUploadImage"
        ></v-md-editor>
      </el-form-item>

      <el-form-item label="封面" prop="coverImage">
        <el-upload
          :action="`http://localhost:8002/file/fileoss/upload`"
          :show-file-list="false"
          :on-success="handleAvatarSuccess"
          :before-upload="beforeAvatarUpload"
          class="avatar-uploader"
        >
          <img v-if="data.imageUrl" :src="data.imageUrl" class="avatar" />
          <!-- <el-icon v-else name="UploadFilled" class="avatar-uploader-icon"></el-icon> -->
          <el-icon v-else class="avatar-uploader-icon">
            <UploadFilled />
          </el-icon>
        </el-upload>
      </el-form-item>

      <el-form-item label="竞赛时间" prop="competitionTime" style="width: 50%">
        <el-date-picker
          v-model="data.dateArr"
          @change="dateChange"
          value-format="YYYY-MM-DD HH:mm:ss"
          type="datetimerange"
          range-separator="-"
          start-placeholder="开始时间"
          end-placeholder="结束时间"
        />
      </el-form-item>

      <el-form-item label="报名截止时间" prop="registrationDeadline">
        <el-date-picker
          type="datetime"
          @change="deadlineChange"
          v-model="data.ruleForm.registrationDeadline"
          placeholder="截止时间"
        />
      </el-form-item>

      <el-form-item style="width: 100%">
        <div style="display: flex; justify-content: center; width: 100%">
          <el-button type="primary" round @click="commit(ruleFormRef)">
            <el-icon>
              <Promotion />
            </el-icon>
            发布
          </el-button>
          <!-- <el-button @click="resetForm(ruleFormRef)">重置</el-button> -->
        </div>
      </el-form-item>
    </el-form>
  </div>
</template>

<script lang="ts">
import { onMounted, defineComponent, reactive, ref } from "vue";
import axios from "axios";
import type { FormInstance, FormRules } from "element-plus";
import { UploadFilled, Promotion } from "@element-plus/icons-vue";
import { competitionAdd } from "@/api/competition";

export default defineComponent({
  components: {
    UploadFilled,
    Promotion,
  },
  setup() {
    //vue3获取ref
    const ruleFormRef = ref<FormInstance>();
    const md = ref(null);

    const data = reactive({
      //表单
      ruleForm: {
        id: 0,
        title: "",
        coverImage: "",
        competitionTime: "",
        registrationDeadline: "",
        content: "",
      },

      //封面显示
      imageUrl: "",

      //竞赛时间（虚设）
      dateArr: "",
    });

    //表单验证
    const validateContent = (rule: any, value: any, callback: any) => {
      if (value === "") {
        return callback(new Error("请输入内容！！"));
      } else {
        callback();
      }
    };

    const validateCoverImage = (rule: any, value: any, callback: any) => {
      if (value === "") {
        return callback(new Error("请上传封面！"));
      } else {
        callback();
      }
    };

    const rules = reactive<FormRules<typeof data.ruleForm>>({
      title: [{ required: true, message: "请输入标题！", trigger: "blur" }],
      competitionTime: [
        { required: true, message: "请输入竞赛时间！", trigger: "blur" },
      ],
      registrationDeadline: [
        { required: true, message: "请输入报名截止时间！", trigger: "blur" },
      ],
      coverImage: [
        { required: true, validator: validateCoverImage, trigger: "blur" },
      ],
      content: [
        { required: true, validator: validateContent, trigger: "blur" },
      ],
    });

    onMounted(async () => {});

    const handleAvatarSuccess = (res: any, file: any) => {
      data.imageUrl = URL.createObjectURL(file.raw);
      console.log(res.data.url);
      data.ruleForm.coverImage = res.data.url;
    };

    const beforeAvatarUpload = () => {};

    // const $imgAdd
    //   const imgAdd = (pos: any, file: any) => {
    // 	console.log('上传图片：断点')
    // 	// console.log(`${File_API.OTHER_URL}`)
    // 	// 第一步.将图片上传到服务器.
    // 	let formdata = new FormData()
    // 	formdata.append('file', file)
    // 	axios({
    // 	  url: `http://localhost:8002/file/fileoss/upload`,
    // 	  method: 'post',
    // 	  data: formdata,
    // 	  headers: { 'Content-Type': 'multipart/form-data' },
    // 	}).then((res) => {
    // 	  // 第二步.将返回的url替换到文本原位置![...](0) -> ![...](url)
    // 	  console.log(res.data.data.url)
    // 	  console.log(md)
    // 	  md.value.$img2Url(pos, res.data.data.url)
    // 	})
    //   }

    const handleUploadImage = (
      event: Event,
      insertImage: any,
      files: File[]
    ) => {
      for (let i in files) {
        const formData = new FormData();
        formData.append("file", files[i]);
        axios.post(`http://localhost:8002/file/fileoss/upload`, formData).then(
          (response) => {
            const { data } = response.data;
            insertImage({
              url: data.url,
              desc: "desc",
            });
          },
          (error) => {
            ElMessage.error(error.message);
          }
        );
      }
    };

    const commit = (formEl: FormInstance | undefined) => {
      // console.log('提交')
      if (!formEl) {
        console.log("表单没找到");
        return;
      }
      formEl.validate(async (valid) => {
        if (valid) {
          console.log("submit!", data.ruleForm);
          console.log(data.ruleForm.registrationDeadline);
          try {
            const res = await competitionAdd(data.ruleForm);
            console.log(res);
          } catch (error) {
            Promise.reject(error);
          }
        } else {
          console.log("error submit!");
          return false;
        }
      });
    };

    const dateChange = (value: any) => {
      console.log(value);
      data.ruleForm.competitionTime = `${value[0]} - ${value[1]}`;
    };

    const deadlineChange = (value: any) => {
      console.log(value);
      data.ruleForm.registrationDeadline = value.Format("yyyy-MM-dd hh:mm:ss");
    };

    const resetForm = (formEl: FormInstance | undefined) => {
      if (!formEl) return;
      formEl.resetFields();
    };

    return {
      data,
      rules,
      handleAvatarSuccess,
      beforeAvatarUpload,
      // imgAdd,
      // File_API,
      handleUploadImage,
      commit,
      resetForm,
      ruleFormRef,
      md,
      dateChange,
      deadlineChange,
    };
  },
});
</script>

<style scoped>
h1 {
  color: blue;
}

.box {
  display: flex;
  justify-content: center;
  width: 100%;
}

/* .el-form{
	display: flex;
	align-items: center;
	flex-direction: column;
	
	} */
.tag {
  margin: 10px;
}
</style>

<!-- 饿了么的样式写在这里避免不生效 -->
<style>
.avatar-uploader .el-upload {
  position: relative;
  overflow: hidden;
  cursor: pointer;
  border: 1px dashed #807d7d;
  border-radius: 6px;
}

.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}

.avatar-uploader-icon {
  width: 150px;
  height: 150px;
  font-size: 28px;
  line-height: 150px;
  color: #409eff;
  text-align: center;
}

.avatar {
  display: block;
  width: 178px;
  height: 178px;
}
</style>
